package org.spbsu.apco.common.task.impl;

import org.spbsu.apco.common.task.core.BaseTask;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Generic task to emulate computations.
 *
 * User: mikpan
 * Date: 3/29/13
 * Time: 4:38 PM
 */
public class GenericComputationTask extends BaseTask<Integer, Integer> {
    public static final int CYCLES_FOR_ONE_SEC = 500 * 1000 * 1000;

    @Override
    public Integer execute(List<Integer> inputData) throws Exception {
        Assert.notEmpty(inputData, "Input is empty.");

        for (int i=0; i<inputData.get(0); i++) {
            //TODO: add operations with memory and io streams
            doCPUOperations(CYCLES_FOR_ONE_SEC);
        }

        return 0;
    }

    private void doCPUOperations(long cycles) {
        int result = 1;
        for (int i=0; i<cycles; i++) {
            result += i + 1;
            result -= i;
        }
    }

    // computing cycle corresponding to 1 second
    public static void main(String[] args) {
        long cL = 1, cR = 800 * 1000 * 1000L;
        GenericComputationTask task = new GenericComputationTask();
        while (cR - cL > 100000) {
            long s = System.nanoTime();
            long average = (cR + cL)/2;
            task.doCPUOperations(average);
            long f = System.nanoTime();

            if (f-s > 1000000000)
                cR = average;
            else
                cL = average;
            System.out.println("cL = " + cL + ", cR = " + cR);
        }
    }

}
